﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsMobile.PocketOutlook;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Reflection;

namespace GSync
{
    public partial class Form1 : Form
    {

        protected Mutex syncObject = new Mutex();
        bool initialized = false;
        int bnSize;
        ImageButton[] buttons;


        public Form1()
        {
            
            
            InitializeComponent();

            GSyncFactory.Instance.Logger.Write("GSync main form started.", "info");


            bnSize = Math.Min(this.Width, this.Height)/3;
            buttons = new ImageButton[]{SyncButton,
            SettingsButton, HelpButton, InfoButton, 
            ClearButton, CloseButton};

            foreach (ImageButton bn in buttons)
            { 
                bn.Width = bnSize;
                bn.Height = bnSize;
            }

            initialized = true;

            if (string.IsNullOrEmpty(GSyncFactory.Instance.SettingsManager.ServerAccountName) ||
                string.IsNullOrEmpty(GSyncFactory.Instance.SettingsManager.ServerPassword))
            {
                SettingsPictureBox_Click(null, null);
                
            }
 
        
            
      
        }



        private void Form1_Resize(object sender, EventArgs e)
        {
            if (!initialized)
                return;
            
            int rotarion = Microsoft.WindowsMobile.Status.SystemState.DisplayRotation;
            if (rotarion == 0)
            {
                
                int xSpan = (this.Width -  bnSize* 2) / 3;
                int[] x = new int[] { xSpan, 2 * xSpan + bnSize };


                int ySpan = (this.Height - bnSize * 3) / 4;
                int[] y = new int[] { ySpan, 2 * ySpan + bnSize, 3 * ySpan + bnSize * 2 };

                
                buttons[0].Location = new Point(x[0], y[0]);
                buttons[1].Location = new Point(x[1], y[0]);
                buttons[2].Location = new Point(x[0], y[1]);
                buttons[3].Location = new Point(x[1], y[1]);
                buttons[4].Location = new Point(x[0], y[2]);
                buttons[5].Location = new Point(x[1], y[2]);
            }
            else
            {

                int xSpan = (this.Width - bnSize * 3) / 4;
                int[] x = new int[] { xSpan, 2 * xSpan + bnSize, 3 * xSpan + bnSize * 2 };

                int ySpan = (this.Height - bnSize * 2) / 3;
                int[] y = new int[] { ySpan, 2 * ySpan + bnSize };


                buttons[0].Location = new Point(x[0], y[0]);
                buttons[1].Location = new Point(x[1], y[0]);
                buttons[2].Location = new Point(x[2], y[0]);
                buttons[3].Location = new Point(x[0], y[1]);
                buttons[4].Location = new Point(x[1], y[1]);
                buttons[5].Location = new Point(x[2], y[1]);
            }
        }

        Guid g = Guid.NewGuid();
        private void ClosePictureBox_Click(object sender, EventArgs e)
        {
            this.Hide();

            System.Windows.Forms.Timer closingTimer = new System.Windows.Forms.Timer();
            closingTimer.Tick += new EventHandler(closingTimer_Tick);
            closingTimer.Interval = 3000;
            closingTimer.Enabled = true;
        }

        void closingTimer_Tick(object sender, EventArgs e)
        {
            if (syncObject.WaitOne(100, false))
            {
                this.Close();
            }
        }

        private void ClearLocalPictureBox_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("This will delete all local contacts.\r\nProceed?","Warning!", 
                                MessageBoxButtons.YesNo, 
                                MessageBoxIcon.Exclamation, 
                                MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                using (OutlookSession session = new Microsoft.WindowsMobile.PocketOutlook.OutlookSession())
                {


                    for (int i = session.Contacts.Items.Count; i > 0; i--)
                    {
                        Contact c = session.Contacts.Items[0];
                        c.Delete();
                    }

                    for (int i = session.Appointments.Items.Count; i > 0; i--)
                    {
                        Appointment a = session.Appointments.Items[0];
                        a.Delete();
                    }


                }

                GSyncFactory.Instance.GetHashCodesCache().Clear();

                MessageBox.Show("Clear succeded.");
            }
        }

        private void SettingsPictureBox_Click(object sender, EventArgs e)
        {
            Settings dlg = new Settings();
            dlg.ShowDialog();
        }
        protected void SetStatus(string statusMessage)
        {
            StatusLabel.Invoke(new SetStatusMessageDelegate(SetStatusSynchronously), statusMessage);
        }

        public delegate void SetStatusMessageDelegate(string msg);
        protected void SetStatusSynchronously(string statusMessage)
        {
            StatusLabel.Text = statusMessage;
        }
        protected void ExecuteSync()
        {

            try
            {
                GSyncFactory.Instance.Logger.Write("starting sync process", "info");
                syncObject.WaitOne();

                if (GSyncFactory.Instance.SettingsManager.SyncContacts)
                {

                    using (SyncManager sMan = GSyncFactory.Instance.BuildContactsSyncManager())
                    {
                        GSyncFactory.Instance.Logger.Write("Synchronizing contacts...", "info");
                        SetStatus("Synchronizing contacts...");
                        sMan.Synchronize();
                        SetStatus("Synchronization compete.");
                        GSyncFactory.Instance.Logger.Write("Contacts synchronization compete.", "info");
                    }
                }

                if (GSyncFactory.Instance.SettingsManager.SyncCalendar)
                {
                    GSyncFactory.Instance.Logger.Write("Synchronizing calendars...", "info");
                    SetStatus("Synchronizing calendars...");
                    using (SyncManager sMan = GSyncFactory.Instance.BuildCalendarSyncManager())
                    {
                        sMan.Synchronize();
                    }
                    SetStatus("Synchronization compete.");
                    GSyncFactory.Instance.Logger.Write("Calendar synchronization compete.", "info");
                }
                GSyncFactory.Instance.Logger.Write("Synchronization compete.", "info");

            }

            catch (Exception ex)
            {
                SetStatus("Sync failed :(");
                GSyncFactory.Instance.Logger.Write(ex, "error");
                
            }
            finally
            {
                syncObject.ReleaseMutex();
            }
        }
       
        private void SyncPictureBox_Click(object sender, EventArgs e)
        {
            Thread syncThread = new Thread(new ThreadStart(ExecuteSync));
            syncThread.Start();
           
            
        }


        protected string CurPath
        {
            get
            {
                return Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
            }
        }

        protected void ShowHelp(string fileName)
        { 
            string helpFilesPath = Path.Combine(CurPath,"help");
            string helpFile = Path.Combine(helpFilesPath, fileName);
            HelpForm frm = new HelpForm();
            frm.HelpURL = @"file://" + helpFile;
            frm.ShowDialog();            
        }
        private void HelpPictureBox_Click(object sender, EventArgs e)
        {
            ShowHelp("gsyncindex.htm");

        }

        private void AboutPictureBox_Click(object sender, EventArgs e)
        {
            ShowHelp("gsyncabout.htm");
        }

        private void Form1_Closing(object sender, CancelEventArgs e)
        {

        }
        
 
    }

        
}